const fs = require('fs')
const path = require('path')
const logger = require('../../util/logger')

function copyAndRenameFiles(imagesRoot, target = __dirname, arr, moreVision = false) {
  arr.forEach(str => {
    const files = fs.readdirSync(imagesRoot).filter(file => file.startsWith(str))
    if (files.length > 0) {
      const newDir = path.join(target, `./${str}`)

      files.forEach(file => {
        const filePath = path.join(imagesRoot, file)
        const newFilePath = path.join(newDir, file)
        fs.copyFileSync(filePath, newFilePath)

        if (file.match(new RegExp(`${str}(\\S*)\\.(\\S+)\\.\\.png`))) {
          const matches = file.match(new RegExp(`${str}(\\S+)\\.(\\S+)\\.png`))
          const newFileName = `${str}${matches && matches[1] ? matches[1] : ''}.png`
          const newFilePathWithNewName = path.join(newDir, newFileName)
          fs.renameSync(newFilePath, newFilePathWithNewName)
          console.log(`${newFileName} 图片处理完成`)
          logger.info(`${newFileName} 图片处理完成`)

          if (moreVision) {
            const newFilePath0 = path.join(path.join(newDir, 'v0'), newFileName)
            const newFilePath3 = path.join(path.join(newDir, 'v3'), newFileName)
            const newFilePath4 = path.join(path.join(newDir, 'v4'), newFileName)
            fs.copyFileSync(newFilePathWithNewName, newFilePath0)
            fs.copyFileSync(newFilePathWithNewName, newFilePath3)
            fs.copyFileSync(newFilePathWithNewName, newFilePath4)
          }
        } else {
          console.log(`${file} 图片复制或命名失败`)
          logger.error(`${file} 图片复制或命名失败`)
        }
      })
    }
  })
}

module.exports = copyAndRenameFiles
